package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.OrderSetting;
import com.itheima.service.OrderSettingService;
import com.itheima.utils.POIUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author Autism
 * @version V1.0
 * @Package com.itheima.controller
 * @date 2019/7/31 21:05
 * @Description
 */
@RestController
@RequestMapping("/ordersetting")
public class OrdersettingController {

    @Reference
    OrderSettingService orderSettingService;

    /**
     * 上传文件
     * @param excelFile
     * @return
     */
    @RequestMapping("/upload")
    public Result upload(MultipartFile excelFile){
        //利用POIUtil读取文件内容
        try {
            List<String[]> stringList = POIUtils.readExcel(excelFile);
            List<OrderSetting> ordersettingList = new ArrayList();
            if (!CollectionUtils.isEmpty(stringList)) {
                stringList.forEach(item -> {
                    OrderSetting orderSetting = new OrderSetting();
                    orderSetting.setOrderDate(new Date(item[0]));
                    orderSetting.setNumber(Integer.parseInt(item[1]));
                    ordersettingList.add(orderSetting);

                });
            }
            orderSettingService.upload(ordersettingList);
        } catch (IOException e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.IMPORT_ORDERSETTING_FAIL);
        }

        return new Result(true,MessageConstant.IMPORT_ORDERSETTING_SUCCESS);
    }

    /**
     * 获取日历显示数据
     * @param date
     * @return
     */
    @RequestMapping("/getCalenderData")
    public Result getCalenderData(String date) { // 2019 -7
        try {
            List<Map> result = orderSettingService.getCalenderData(date);
            return new Result(true, MessageConstant.GET_ORDERSETTING_SUCCESS, result);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_ORDERSETTING_FAIL);
        }
    }

    /**
     * 根据日期设置可预约人数
     * @param orderSetting
     * @return
     */
    @RequestMapping("/setDataByOrderDate")
    public Result setDataByOrderDate(@RequestBody OrderSetting orderSetting) {
        try {
            orderSettingService.setDataByOrderDate(orderSetting);
        } catch (Exception e) {
            return new Result(false, MessageConstant.ORDERSETTING_FAIL);
        }
        return new Result(true, MessageConstant.ORDERSETTING_SUCCESS);
    }
}
